package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<String> login(@RequestBody Employee employee){
        log.info("employee:{}",employee);
        //添加MD5算法
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //添加条件
        LambdaQueryWrapper<Employee> lqw =new LambdaQueryWrapper<>();
        lqw.eq(employee.getUsername()!=null,Employee::getUsername,employee.getUsername());
        Employee es = employeeService.getOne(lqw);

        if (es==null){
            return R.error("用户不存在");
        }
        if (!es.getPassword().equals(password)){
            return R.error("密码不正确");
        }
        if (es.getStatus()==0){
            return R.error("该用户已禁用");
        }
        return R.success("登录成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Employee> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Employee> lqw =new LambdaQueryWrapper<>();
        lqw.like(name!=null,Employee::getUsername,name);
        lqw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo,lqw);

        int count = employeeService.count();
        return R.success(pageInfo);
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee){
        log.info(employee.toString());
        LambdaQueryWrapper<Employee> lqw =new LambdaQueryWrapper<>();
        lqw.eq(employee.getIdNumber()!=null,Employee::getUsername,employee.getIdNumber());
        Employee one = employeeService.getOne(lqw);
        if (one==null){
            //给新用户设置一个密码
            employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            employeeService.save(employee);
            return R.success("保存成功");
        }
        return R.error("账号已存在");
    }
}
